package SingleIinkSentinel;
import java.util.Iterator;
import java.util.function.Consumer;

//整体
public class SingleLists implements Iterable<Integer>{
    //头节点
    private final Node hand = new Node(0,null);


    //节点
    private static class Node {
        //数据
        private int data;
        //指向下一个节点
        private Node next;

        public Node() {
        }

        public Node(int data, Node next) {
            this.data = data;
            this.next = next;
        }
    }

    //实现头插节点
    public void addFirst(int data) {
        //对以上代码进行简化得以下代码：
        //hand.next = new Node(data,hand.next);
        insert(0,data);

    }

    //遍历方式：打印方式
    public void myPrint(){
        for (Node p = hand.next;p !=null;p = p.next){
            System.out.println(p.data);
        }
    }

    //遍历方式:实现forEach，由于跟以下的代码有冲突，先改名为 myForEach。
    public void myForEach(Consumer<Integer> consumer){
        for (Node p = hand.next; p != null;p = p.next){
            consumer.accept(p.data);
        }
    }

    //遍历方式：使用迭代器循环
    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            Node p = hand.next;
            @Override
            public boolean hasNext() {
                return p != null;
            }

            @Override
            public Integer next() {
                int k = p.data;
                p = p.next;
                return k;
            }
        };
    }

    //尾插节点
    public void addLast(int data) {
        Node p = hand;
        while (p.next != null){
            p = p.next;
        }
        p.next = new Node(data,null);
    }

    //根据索引获取某个节点
    private Node findNode(int index) {
        int i = -1;
        for (Node p = hand ; p != null ; p = p.next,i++)
        {
            if (i == index) {
                return p;
            }
        }
        return null;
    }

    //根据索引得到对应的数据
    public int get(int index) {
        Node p = findNode(index);
        if (p == null){
            throw new RuntimeException("找不到该索引!!!");
        }
        return p.data;
    }

    //根据索引插入数据
    public void insert(int index , int data){
        Node prev = findNode(index - 1);
        if (prev == null){
            throw new RuntimeException("index is illegal");
        }
        prev.next =  new Node(data,prev.next);
    }

    //头删节点
    public void removeFirst() {
        //hand = hand.next;
        remove(0);
    }

    //根据索引来删除节点
    public void remove(int index) {
        Node prev = findNode(index - 1);
        if (prev == null){
            throw new RuntimeException("There are no nodes anymore");
        }
        Node move = prev.next;
        if (move == null) {
            throw new RuntimeException("There are no nodes anymore");
        }
        prev.next = move.next;
    }
}